package at.jaki.ubb.crawling.appThreads;

import java.util.Collection;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.log4j.Logger;

import at.jaki.ubb.crawling.model.DataFinderResult;
import at.jaki.ubb.crawling.model.RawData;
import at.jaki.ubb.crawling.model.Target;

/**
 * This singleton will run on a separate thread. It is responsible for managing
 * the results of the datafinders.
 * 
 * @author Attila Jakabfi
 * 
 */
public final class DataFinderResultManager extends AbstractResultManager<DataFinderResult<?, ?>> {

	private static final Logger LOG = Logger.getLogger(DataFinderResultManager.class);

	private static DataFinderResultManager instance;

	public static synchronized DataFinderResultManager getInstance() {
		if (instance == null) {
			instance = new DataFinderResultManager();
		}
		return instance;
	}

	/**
	 * Private constructor for singleton.
	 */
	private DataFinderResultManager() {
		LOG.info("Creating DataFinder Result Manager");
	}

	@Override
	public void resolveDoneTask(Future<DataFinderResult<?, ?>> future) {
		try {
			DataFinderResult<?, ?> dataFinderResult = future.get();
			Collection<?> rawDataCollection = dataFinderResult.getRawDataCollection();
			Collection<?> targetCollection = dataFinderResult.getTargetCollection();
			
			LOG.debug("Found terminated data finder task with "+rawDataCollection.size()+" raw datas and "+targetCollection.size()+" targets");

			TargetQueue targetQueue = TargetQueue.getInstance();
			for (Object o : targetCollection) {
				if (o instanceof Target) {
					Target<?> t = (Target<?>) o;
					targetQueue.push(t);
				} else {
					LOG.error("Found element in target Collection, of different class then at.jaki.ubb.crawling.model.Target. Will skip this element");
					LOG.error("Incompatible element: " + o.toString());
				}
			}

			DataSet dataSet = DataSet.getInstance();
			for (Object o : rawDataCollection) {
				if (o instanceof RawData) {
					RawData<?> rd = (RawData<?>) o;
					dataSet.add(rd);
				} else {
					LOG.error("Found element in data Collection, of different class then at.jaki.ubb.crawling.model.RawData. Will skip this element");
					LOG.error("Incompatible element: " + o.toString());
				}
			}

		} catch (InterruptedException e) {
			LOG.warn("Interrupted " + e.getLocalizedMessage());
		} catch (ExecutionException e) {
			LOG.warn(e.getClass().getName() + " : " + e.getLocalizedMessage());
		}

	}
	
}
